var markerArray = [];
var reloadMaps = [];
var vResultsFrom = 0;
var numOfResults = 10;
var jsonInfo = [];
var infowindow;
var test;

//when the page has loaded execute loadList()
$(document).ready(function() {

	var newHeights = $(window).height()-$("#navigation").outerHeight()-$("#footer").outerHeight()-$("#header").outerHeight(true)-$("#map_wrapper").css("margin-top").replace("px", "");
	$("#map_wrapper").height(newHeights);
	$("#map_canvas").height(newHeights);

	newHeights = newHeights -$("#marker_selection").outerHeight()-$("#locate_btn").outerHeight();
	$("#list").height(newHeights);



	placeMarkers();

});

function placeMarkers() {

	var icon;
	// google maps stuff

	//default position for map
	var latlng = new google.maps.LatLng(33.783409, -117.884674);
	//defualt options for map

	var defaultBounds = new google.maps.LatLngBounds(
			new google.maps.LatLng(33.783409, -117.884674),
			new google.maps.LatLng(33.783409, -117.884674));

	var input = document.getElementById('address');
	var options = {
			bounds: defaultBounds,
			types: ['geocode'],
			offset:-20
	};	

	var autocomplete = new google.maps.places.Autocomplete(input, options);
	
	var myOptions = {
			zoom : 11,
			center : latlng,
			mapTypeId : google.maps.MapTypeId.HYBRID
			//type of map HYBRID/ROADMAP/SATELLITE/TERRAIN
	};
	var map = new google.maps.Map(document.getElementById('map_canvas'),
			myOptions);
	
	autocomplete.bindTo('bounds' , map);

	infowindow = new google.maps.InfoWindow({
		content : "temp"
	});


	$.getJSON('get_map_points.php', function(output) {
		$.each(output, function(i) {
			var lat = output[i]['lat'];
			var lng = output[i]['lng'];
			var id = output[i]['id'];
			var orgName = output[i]['orgName'];
			var category = output[i]['category'];
			var address1 = output[i]['address1'];
			var address2 = output[i]['address2'];

			var latlng = new google.maps.LatLng(lat, lng);

			switch (category) {
			case "other":
				icon = new google.maps.MarkerImage('images/vineyard-2.png',
						new google.maps.Size(32, 37), new google.maps.Point(0,
								0), new google.maps.Point(16, 37));
				break;
			case "farm":
				icon = new google.maps.MarkerImage('images/yellow.png',
						new google.maps.Size(32, 37), new google.maps.Point(0,
								0), new google.maps.Point(16, 37));
				break;
			case "csa":
				icon = new google.maps.MarkerImage('images/blue.png',
						new google.maps.Size(32, 37), new google.maps.Point(0,
								0), new google.maps.Point(16, 37));
				break;
			case "farmers_market":
				icon = new google.maps.MarkerImage('images/purple.png',
						new google.maps.Size(32, 37), new google.maps.Point(0,
								0), new google.maps.Point(16, 37));
				break;
			case "orchards":
				icon = new google.maps.MarkerImage('images/white.png',
						new google.maps.Size(32, 37), new google.maps.Point(0,
								0), new google.maps.Point(16, 37));
				break;
			case "community_garden":
				icon = new google.maps.MarkerImage('images/turq.png',
						new google.maps.Size(32, 37), new google.maps.Point(0,
								0), new google.maps.Point(16, 37));
				break;
			}

			var marker = new google.maps.Marker({
				position : latlng,
				map : map,
				icon : icon,
				title : orgName
			});

			marker.html = $(output[i]['infobox']).html();
			marker.category = category;
			marker.id = id;
			marker.address = address1.concat(address2);
			

			google.maps.event.addListener(marker, 'click', function() {
				infowindow.setContent(this.html);
				infowindow.open(map, this);
			});
			markerArray.push(marker);
		});
	});
}
function openWindow(i) {
	google.maps.event.trigger(markerArray[i], 'click');
}

function toggleVisible(theCategory) {
	infowindow.close();
	var notCheck = $('input[type=checkbox]').not(':checked').length;

	if ((theCategory == 'all') && ($('input[id = all]').is(':checked'))){
		$('input[id = farm]').attr('checked',true);
		$('input[id = farmers_market]').attr('checked',true);
		$('input[id = community_garden]').attr('checked',true);
		$('input[id = orchards]').attr('checked',true);
		$('input[id = csa]').attr('checked',true);
		$('input[id = other]').attr('checked',true);
	}else if ((theCategory == 'all') && !$('input[id = all]').is(':checked')){
		$('input[id = farm]').attr('checked',false);
		$('input[id = farmers_market]').attr('checked',false);
		$('input[id = community_garden]').attr('checked',false);
		$('input[id = orchards]').attr('checked',false);
		$('input[id = csa]').attr('checked',false);
		$('input[id = other]').attr('checked',false);
	}else{
		if(	$('input[id = farm]').is(':checked')&& 
				$('input[id = farmers_market]').is(':checked')&&
				$('input[id = community_garden]').is(':checked')&&
				$('input[id = orchards]').is(':checked')&&
				$('input[id = csa]').is(':checked')&&
				$('input[id = other]').is(':checked')){
			$('input[id = all]').attr('checked',true);
		}else
			$('input[id = all]').attr('checked',false);
	}

	for ( var i = 0; i < markerArray.length; i++) {
		var marker = markerArray[i];

		if (theCategory == 'all'){

			if($('input[id = all]').is(':checked'))
				marker.setVisible(true);
			else
				marker.setVisible(false);
		}
		else if (markerArray[i].category == theCategory){
			if($('input[id = '+theCategory+']').is(':checked'))
				marker.setVisible(true);
			else
				marker.setVisible(false);
		}
	}

}

function FindClosest(){
	$("#list").empty();
	var radius = document.getElementById("radius").value;
	var geocoder = new google.maps.Geocoder();
	var address = document.getElementById("address").value;
	var meterspermile = 1609.344;
	var newDistance = 0;
	var visibleMarkers = [];
	var tempHtml;
	if($("#address").val() == "")
		$("#list").append("<div style = \"color : red\">*Please Enter an Address*</div>");
	else{

		geocoder.geocode({'address':address},function(results, status){
			if (status == google.maps.GeocoderStatus.OK)
			{

				if(results.length == 1){
					$("input[type=checkbox]:checked").each(function(){
						toggleVisible(this.id);
					}); 
					$.each(markerArray,function(i,value) {
						if(value.getVisible()){
							newDistance =
								google.maps.geometry.spherical.computeDistanceBetween(results[0].geometry.location,value.position)
								/meterspermile;
							if (newDistance > radius)
								value.setVisible(false);
							else{
								value.distance = newDistance;
								value.MarkerArrayPosition = i;
								visibleMarkers.push(value);
							}


						}
					});

					visibleMarkers.sort(sortNumber);
					for(var i = 0; i < visibleMarkers.length; i++){
						tempHtml = visibleMarkers[i]['title'];
						$("#list").append("<div onclick = \"openWindow("+visibleMarkers[i].MarkerArrayPosition+")\">"+
								tempHtml+"<br><a href= \"#\">Distance: "+visibleMarkers[i]['distance'].toFixed(2)+" miles</a><br></div>");
						
						var address = results[0].formatted_address;
						address = address.replace(/\s+/g,"+");
						address = address.replace(/,/g,"");
						var destination =  visibleMarkers[i]['address'];
						destination = destination.replace(/\s+/g,"+");
						destination = destination.replace(/,/g,"");
						
						var url = "<a href=\"http://maps.google.com/maps?saddr="+address+"&daddr="+destination+"\"\>Driving Directions</a><br>";
						$("#list").append(url);
						
						
					}
				}
				else{
					for(var i = 0; i<results.length;i++){
						$("#list").append("did you mean?<br>");
					}
					
				}





			}else{
				$("#list").append("<div style = \"color : red\">*Address Not Found*</div>");
			}
		});	
	}


}	

function sortNumber(a,b)
{
	return a.distance - b.distance;
}


